package com.lst.tools.mybatis.utils;

import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.util.List;

/**
 * @author: Frank
 * @date: 2019/9/26 15:33
 * @version: V1.0
 */
public class ExpandSqlUtils {

    public static final String getInsertNotExistSql() {
        return "<script> INSERT INTO %s %s SELECT %s FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM %s %s);</script>";
    }

    public static final String getAllInsertSqlColumnMaybeIf(TableInfo tableInfo, final String prefix) {
        List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        StringBuilder sql = new StringBuilder();
        int size = fieldList.size();
        for (int i = 0; i < size; i++) {
            TableFieldInfo tableFieldInfo = fieldList.get(i);
            sql.append("<if test=\"");
            if (StringUtils.isNotEmpty(prefix)) {
                sql.append(prefix);
            }
            sql.append(tableFieldInfo.getProperty()).append(" != null\">")
                    .append(tableFieldInfo.getColumn()).append(",</if>");
            if (i != size - 1) {
                sql.append("\n");
            }
        }
        return sql.toString();
    }

    public static String getAllInsertSqlPropertyMaybeIf(TableInfo tableInfo, String prefix) {
        List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        StringBuilder sql = new StringBuilder();
        int size = fieldList.size();
        for (int i = 0; i < size; i++) {
            TableFieldInfo tableFieldInfo = fieldList.get(i);
            sql.append("<if test=\"");
            if (StringUtils.isNotEmpty(prefix)) {
                sql.append(prefix);
            }
            sql.append(tableFieldInfo.getProperty()).append(" != null\">").append("#{");
            if (StringUtils.isNotEmpty(prefix)) {
                sql.append(prefix);
            }
            sql.append(tableFieldInfo.getProperty()).append("}").append(",</if>");
            if (i != size - 1) {
                sql.append("\n");
            }
        }
        return sql.toString();
    }

    public static String getIsNullOrderBy(String fieldName, boolean isNullTop) {
        StringBuilder sql = new StringBuilder();
        sql.append("if(isnull(").append(fieldName).append("),");
        if (isNullTop) {
            sql.append("0,1");
        } else {
            sql.append("1,0");
        }
        sql.append(")");
        return sql.toString();
    }
}
